//
//  CustomTabbar.m
//  飞天FM
//
//  Created by Song on 2017/6/2.
//  Copyright © 2017年 SongZhaoJun. All rights reserved.
//  自定义TabBar

#import "CustomTabbar.h"
#import "MiddleView.h"
#import "UIView+Extension.h"
#import "UIColor+Extension.h"
#import "UIImage+FTImage.h"
#import "CALayer+PauseAimate.h"
#import "Common.h"

#import <objc/runtime.h>
@interface CustomTabbar()

@property (nonatomic,strong) MiddleView* middleView;

@end

@implementation CustomTabbar

/**
 单例

 @return 返回唯一的自身
 */
+ (instancetype)shareInstance {
    
    static CustomTabbar* tabbarC;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        tabbarC = [[CustomTabbar alloc] init];
    });
    return tabbarC;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        
        NSBundle* currentBundl = [NSBundle bundleForClass:self.class];
        NSString* imagePath = [currentBundl pathForResource:@"tabbar_bg@2x.png" ofType:nil inDirectory:@"FTFMMain.bundle"];
    
        [self setBackgroundImage:[UIImage imageWithContentsOfFile:imagePath]];
        
    }
    return self;
}


-(void)layoutSubviews {
    
    [super layoutSubviews];
    
    // 按钮宽度
    CGFloat btnW = self.width / 5;
    int index = 0;
    
    // 添加中间按钮
    for (UIView* btn in self.subviews) {
        if ([btn isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
             btn.width = btnW;
             if (index == 2) {
                 index++;
                
                 [self createMiddleView];
             }
              btn.x = index * btnW;
              index++;
        }
    }
    
}

- (void)createMiddleView {
    
    self.middleView = [MiddleView shareInstance];
    [self addSubview:self.middleView];
    self.middleView.centerX = self.width * 0.5;
    self.middleView.y = -15;
    
    __weak CustomTabbar*  weakSelf = self;
    self.middleView.middleClickBlock = ^(BOOL isPlaying) {
        [[NSNotificationCenter defaultCenter] postNotificationName:MiddleViewPlayState object:@(!weakSelf.middleView.isPlaying)];
    };
    
}

-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    // 设置允许交互的区域
    // 1.转换点击在tabbar上的坐标点，到中间按钮上
    CGPoint pointInCenterBtn = [self convertPoint:point toView:self.middleView];

    // 2.确定中间按钮的圆心
    CGPoint middlebtnCenter = CGPointMake(33, 33);
    
    // 3.计算点击的位置距离圆心的距离
    CGFloat distance = sqrt(pow(pointInCenterBtn.x - middlebtnCenter.x, 2) + pow(pointInCenterBtn.y - middlebtnCenter.y, 2));
    
    // 4.判定中间按钮区域之外
    if (distance > 33 && pointInCenterBtn.y < 18) {
        return NO;
    }
    
    return true;
}


@end
